package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.ContractAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessHistory;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.DhUtil;
import com.gongpingjialoan.widget.LoadingDialog;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/5/19.  联系记录
 */
public class ContractActivity extends BaseActivity implements View.OnClickListener, NetDataJson.OnNetDataJsonListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {

    private PullToRefreshListView pullToRefreshListView;

    private ImageView nodataImageView;

    private ListView listView;

    private View footView;

    private List<AssessHistory> mAssessHistories;

    private NetDataJson mNetDataJson;

    private ContractAdapter mContractAdapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    private PopupWindow mPopupWindow;

    private View popupView;

    private TextView tx1, tx2, tx3;

    private View selectView, popup_main;

    private NetDataJson addResultNetDataJson;

    private LoadingDialog loadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "my_contactRecord";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browse_layout);
        setTitle("联系记录");
        loadingDialog = new LoadingDialog(this);
        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        nodataImageView = (ImageView) findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);

        mAssessHistories = new ArrayList<>();
        mContractAdapter = new ContractAdapter(mAssessHistories, this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(mContractAdapter);
        listView.setOnItemClickListener(this);
        listView.removeFooterView(footView);
        listView.setClipToPadding(false);
        popupView = LayoutInflater.from(this).inflate(R.layout.contract_popup, null);
        mPopupWindow = new PopupWindow(popupView, DhUtil.dip2px(this, 95), ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        ColorDrawable cd = new ColorDrawable(0x000000);
        mPopupWindow.setBackgroundDrawable(cd);
        popup_main = popupView.findViewById(R.id.popup_main);
        tx1 = (TextView) popupView.findViewById(R.id.tx1);
        tx2 = (TextView) popupView.findViewById(R.id.tx2);
        tx3 = (TextView) popupView.findViewById(R.id.tx3);
        tx1.setOnClickListener(this);
        tx2.setOnClickListener(this);
        tx3.setOnClickListener(this);

        mNetDataJson = new NetDataJson(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 300);

    }

    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nodataImageView.setVisibility(View.GONE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.addParam("record_type", "contact");
        mNetDataJson.setUrl(API.collectHistory);
        mNetDataJson.request("get");
    }


    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            // Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return;
        AssessHistory carSource = (AssessHistory) view.getTag(R.id.tag_second);
        Intent intent = new Intent();
        if ("promo_car".equals(carSource.record_type)) {
            intent.setClass(this, DiscountDetailActivity.class);
            intent.putExtra("typevalue", String.valueOf(carSource.promo_car_id));
            startActivity(intent);
        } else {
            intent.setClass(this, CarBuyDetailActivity.class);
            intent.putExtra("typevalue", String.valueOf(carSource.car_id));
            intent.putExtra("type", "fromHistory");
            intent.putExtra("from", "favorite");
            startActivity(intent);
        }
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (addResultNetDataJson != null) {
            addResultNetDataJson.cancelTask();
            addResultNetDataJson = null;
        }

    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            mAssessHistories.clear();
            mContractAdapter.setData(mAssessHistories);
        }
        try {
            jsonArray = json.getJSONArray("records");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nodataImageView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                return;
            }

            for (int i = 0; i < jsonArray.length(); i++) {
                AssessHistory ah = new AssessHistory();
                JSONObject object = jsonArray.getJSONObject(i);
                ah.city = object.getString("city");
                ah.mile = object.getString("mile");
                ah.create_time = object.getString("create_time");
                ah.contact_result = object.getString("contact_result");
                ah.title = object.getString("title");
                ah.record_id = object.getString("record_id");
                ah.price = object.getString("price");
                ah.year = object.getString("year");
                ah.type = object.getString("type");
                ah.review = object.getString("review");
                ah.review_type = object.getString("review_type");
                ah.url = object.getString("thumbnail");
                ah.car_id = object.getString("car_id");
                mAssessHistories.add(ah);
            }
            int page_num = json.getInt("total_page");
            if (page_num == mPage) {
                mHasMore = false;
            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            nodataImageView.setVisibility(View.VISIBLE);
            Toast.makeText(this, "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        mContractAdapter.setData(mAssessHistories);
        pullToRefreshListView.onRefreshComplete();
        mIsLoadingMore = false;

    }


    public void showPopup(View v) {
        selectView = v;

        TextView popupTextView = (TextView) v.findViewById(R.id.setting);
        final ImageView popupImageView = (ImageView) v.findViewById(R.id.image);
        popupImageView.setImageResource(R.drawable.contract_up);

        int[] location = new int[2];
        selectView.getLocationOnScreen(location);
        if (location[1] + DhUtil.dip2px(this, 130) > getResources().getDisplayMetrics().heightPixels) {
            popup_main.setBackgroundResource(R.drawable.contract_up_bg);
            mPopupWindow.showAsDropDown(popupTextView, -DhUtil.dip2px(this, 32), -DhUtil.dip2px(this, 120) - selectView.getHeight());
        } else {
            popup_main.setBackgroundResource(R.drawable.contract_bg);
            mPopupWindow.showAsDropDown(popupTextView, -DhUtil.dip2px(this, 32), 0);
        }

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popupImageView.setImageResource(R.drawable.contract_down);
            }
        });
    }

    private String typeNmae, type;

    @Override
    public void onClick(final View v) {
        if (v == tx1 || v == tx2 || v == tx3) {
            mPopupWindow.dismiss();
            if (v == tx1) {
                type = "SD";
                typeNmae = "已卖出";
            } else if (v == tx2) {
                type = "IE";
                typeNmae = "信息错误";
            } else {
                type = "PE";
                typeNmae = "电话错误";
            }
            final int pos = (int) selectView.getTag();

            if (addResultNetDataJson == null) {
                addResultNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                    @Override
                    public void onDataJsonError(String errorMessage) {
                        loadingDialog.dismiss();
                        Toast.makeText(ContractActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onDataJsonUpdate(JSONObject json) {
                        loadingDialog.dismiss();
                        TextView settingTextView = (TextView) selectView.findViewById(R.id.setting);
                        ImageView settingImageView = (ImageView) selectView.findViewById(R.id.image);
                        selectView.setOnClickListener(null);
                        TextView tv = (TextView) v;
                        settingTextView.setText(typeNmae);
                        settingImageView.setVisibility(View.GONE);
                    }
                });
            }
            loadingDialog.show();
            addResultNetDataJson.addParam("car_id", mAssessHistories.get(pos).car_id);
            addResultNetDataJson.addParam("result_code", type);
            addResultNetDataJson.setUrl(API.add_contact);
            addResultNetDataJson.request("post");

        }
    }
}
